
//-------------------------------------------------------------
#include "log.h"
#include "scheduler.h"

namespace tt01{

static learnco::Logger::ptr g_logger = learnco::LoggerMgr::GetInstance()->getLogger("user");

void fun1(){
    LEARNCO_LOG_DEBUG(g_logger) << "执行FUN1 NO.1" ;
    learnco::Fiber::YieldToHold();
    LEARNCO_LOG_DEBUG(g_logger) << "执行FUN1 NO.2" ;
}

void fun2(){
    LEARNCO_LOG_DEBUG(g_logger) << "执行FUN2 NO.1" ;
    learnco::Fiber::YieldToHold();
    LEARNCO_LOG_DEBUG(g_logger) << "执行FUN2 NO.2" ;
}

void test_scheduler()
{
learnco::Scheduler sc(24);
    for(int i=0; i<1000; i++)
    {
        sc.scheduler(&fun1);
        sc.scheduler(&fun2);
    }
    sc.start();
    sc.stop();
    LEARNCO_LOG_DEBUG(g_logger) << "Scheduler结束" ;
}

}
//namespace
//-------------------------------------------------------------


//-------------------------------------------------------------
#include "fiber.h" 
#include "thread.h"
#include "scheduler.h"
#include <random>
#include <iostream>
#include <atomic>
#include <sys/syscall.h>
#include <unistd.h>
#include <vector>
#include <chrono>

namespace tt02
{
    using std::default_random_engine;
    using std::uniform_int_distribution;

    default_random_engine e;
    uniform_int_distribution<unsigned> u(1, 100); //随机数分布对象
    std::atomic<size_t> concurrence_id = {0};

    void fun1() 
    {
        // .... 
        // string s = read()
        usleep(u(e));
        // handle(s); do someting...
    }

    //使用多线程方式创建1W个并发任务
    void test_threadco()
    {
 auto start = std::chrono::system_clock::now();
        std::vector<learnco::Thread::ptr> thrs;
        thrs.reserve(10000);
        for(int i=0; i<10000; i++)
        {
            learnco::Thread::ptr thr(new learnco::Thread(&fun1));
            thrs.push_back(thr);
        }
        for(size_t i = 0; i < thrs.size(); ++i) {
            thrs[i]->join();
        }
auto end = std::chrono::system_clock::now();
        std::cout << "  for-1W thread concurrence, cost ";
        std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
    }

    //使用协程方式创建1W个并发任务,由于没有hook sleep函数，这里相当于线程池
    void test_fiberco()
    {
auto start = std::chrono::system_clock::now();

learnco::Scheduler sc(24);
        for(int i=0; i<10000; i++)
        {
            sc.scheduler(&fun1);
        }
        sc.start();
        sc.stop();
auto end = std::chrono::system_clock::now();
        std::cout << "  for-1W fiber concurrence, cost ";
        std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << "ms" << std::endl;
    }

} //namespace
//-------------------------------------------------------------



using namespace learnco;
int main()
{
    tt01::test_scheduler();
    tt02::test_threadco();
    tt02::test_fiberco();
    return 0;
}